import { Button, Card, Descriptions, Form, Input, InputNumber, Spin, message } from "antd";
import { useState } from "react";
import { getScanApi, getToken } from "../utils/client";

function ScanPanel() {
    const [hostName, setHostName] = useState("");
    const [fromPort, setFromPort] = useState(1);
    const [toPort, setToPort] = useState(1024);
    const [inRun, setInRun] = useState(false);
    const [portList, setPortList] = useState<number[]>([]);

    const runScan = async () => {
        setInRun(true);
        setPortList([]);

        const api = getScanApi();
        try {
            const res = await api.scanTcpportPost({
                scanTcpportPostRequest: {
                    token: getToken(),
                    addr: hostName,
                    from: fromPort,
                    to: toPort,
                },
            });
            setPortList(res.sort());
        } catch (e) {
            console.log(e);
            message.error("扫描失败");
        }
        setInRun(false);
    };

    return (
        <Card bordered={false} bodyStyle={{ height: "calc(100vh - 120px)", overflowY: "auto" }}
            extra={
                <Form layout="inline">
                    <Form.Item label="网络地址">
                        <Input value={hostName} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setHostName(e.target.value.trim());
                        }} disabled={inRun} />
                    </Form.Item>
                    <Form.Item label="开始端口">
                        <InputNumber value={fromPort} min={1} max={65535} precision={0} controls={false}
                            onChange={value => setFromPort(value as number)} disabled={inRun} />
                    </Form.Item>
                    <Form.Item label="结束端口">
                        <InputNumber value={toPort} min={fromPort} max={65535} precision={0} controls={false}
                            onChange={value => setToPort(value as number)} disabled={inRun} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" disabled={inRun || hostName == ""} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            runScan();
                        }}>扫描</Button>
                    </Form.Item>
                </Form>
            }>
            {inRun == true && <Spin />}
            {inRun == false && (
                <Descriptions column={1}>
                    <Descriptions.Item label="开放端口">{portList.map(item => item.toFixed(0)).join(",")}</Descriptions.Item>
                </Descriptions>
            )}
        </Card>
    );
}

export default ScanPanel;